import 'package:flutter/material.dart';
import 'package:ducafe_ui_core/ducafe_ui_core.dart';
import 'package:google_fonts/google_fonts.dart';
import '../../core/models/map_location_entity.dart';
import '../../core/models/user_model.dart';
import '../../core/data/default_map_data.dart';
import '../../core/di/service_locator.dart';

// 地图墙页面
class VamosMapWallInterface extends StatefulWidget {
  const VamosMapWallInterface({Key? key}) : super(key: key);

  @override
  State<VamosMapWallInterface> createState() => _VamosMapWallInterfaceState();
}

class _VamosMapWallInterfaceState extends State<VamosMapWallInterface>
    with TickerProviderStateMixin {
  List<MapLocationEntity> _mapLocations = [];
  String? _selectedLocationId;
  late AnimationController _animationController;
  late Animation<double> _scaleAnimation;
  late Animation<Offset> _slideAnimation;

  @override
  void initState() {
    super.initState();
    _initializeMapData();
    _setupAnimations();
  }

  void _initializeMapData() {
    // 获取默认地图位置数据
    _mapLocations = DefaultMapDataCollection.mapLocations;
  }

  void _setupAnimations() {
    _animationController = AnimationController(
      duration: Duration(milliseconds: 200),
      vsync: this,
    );

    _scaleAnimation = Tween<double>(begin: 1.0, end: 1.15).animate(
      CurvedAnimation(parent: _animationController, curve: Curves.easeOut),
    );

    _slideAnimation = Tween<Offset>(
      begin: Offset.zero,
      end: Offset(0, -0.15),
    ).animate(
      CurvedAnimation(parent: _animationController, curve: Curves.easeOut),
    );
  }

  @override
  void dispose() {
    _animationController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Container(
        width: double.infinity,
        height: double.infinity,
        decoration: BoxDecoration(
          image: DecorationImage(
            image: AssetImage('assets/images/my_background.png'),
            fit: BoxFit.cover,
          ),
        ),
        child: SafeArea(
          bottom: false,
          child: Column(
            children: [
              _buildTopBar(),
              Expanded(
                child: SingleChildScrollView(
                  child: Column(
                    children: [_buildMapContent(), _buildBottomBar()],
                  ),
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }

  // 构建底部栏
  Widget _buildBottomBar() {
    return SizedBox(
      width: double.infinity,
      height: 100.h,
      child: Text.rich(
        TextSpan(
          children: [
            TextSpan(
              text: 'Print \n',
              style: TextStyle(
                color: const Color(0xFFF7CEBA),
                fontSize: 36.sp,
                fontFamily:
                    GoogleFonts.goblinOne(
                      fontWeight: FontWeight.w400,
                    ).fontFamily,
                fontWeight: FontWeight.w400,
              ),
            ),
            TextSpan(
              text: 'the Map Wall',
              style: TextStyle(
                color: const Color(0xFFCEF672),
                fontSize: 36.sp,
                fontFamily:
                    GoogleFonts.goblinOne(
                      fontWeight: FontWeight.w400,
                    ).fontFamily,
                fontWeight: FontWeight.w400,
              ),
            ),
          ],
        ),
      ),
    ).paddingHorizontal(16.w);
  }

  // 构建顶部栏
  Widget _buildTopBar() {
    return Container(
      height: 56.h,
      child: Row(
        children: [
          // 返回按钮
          Icon(Icons.arrow_back, size: 26.sp, color: Colors.white)
              .paddingHorizontal(16.w)
              .inkWell(
                onTap: () {
                  Navigator.of(context).pop();
                },
              ),

          // 标题
          Expanded(
            child: Text('Map Wall')
                .fontSize(16.sp)
                .fontFamily(
                  GoogleFonts.goblinOne(fontWeight: FontWeight.w400).fontFamily,
                )
                .textColor(Colors.white)
                .textAlignment(TextAlign.center),
          ),

          // 占位，保持对称
          SizedBox(width: 56.w),
        ],
      ),
    );
  }

  // 构建地图内容
  Widget _buildMapContent() {
    return Container(
      margin: EdgeInsets.symmetric(horizontal: 16.w),
      child: Stack(
        children: [
          // 背景地图
          _buildMapBackground(),

          // 地图位置点
          ..._mapLocations.map((location) => _buildLocationPoint(location)),
        ],
      ),
    );
  }

  // 构建地图背景
  Widget _buildMapBackground() {
    return Container(
      width: double.infinity,
      child: Image.asset(
        'assets/images/wall_map.png',
        fit: BoxFit.fitWidth, // 恢复自适应宽度
        errorBuilder: (context, error, stackTrace) {
          return Container(
            height: 400.h,
            color: Colors.grey[300],
            child:
                Icon(
                  Icons.image_not_supported,
                  size: 50.sp,
                  color: Colors.grey[600],
                ).center(),
          );
        },
      ),
    );
  }

  // 构建单个位置点
  Widget _buildLocationPoint(MapLocationEntity location) {
    final bool isSelected = _selectedLocationId == location.locationId;

    return Positioned(
      left: location.positionX * (MediaQuery.of(context).size.width - 32.w),
      top: location.positionY * 400.h, // 恢复原来的地图高度400.h
      child: AnimatedBuilder(
        animation: _animationController,
        builder: (context, child) {
          return Transform.translate(
            offset:
                isSelected
                    ? Offset(0, _slideAnimation.value.dy * 20)
                    : Offset.zero,
            child: Transform.scale(
              scale: isSelected ? _scaleAnimation.value : 1.0,
              child: _buildLocationItem(location),
            ),
          );
        },
      ),
    );
  }

  // 构建位置项
  Widget _buildLocationItem(MapLocationEntity location) {
    final bool isSelected = _selectedLocationId == location.locationId;

    return Column(
      mainAxisSize: MainAxisSize.min,
      children: [
        // 用户头像
        Container(
          width: 40.w,
          height: 40.w,
          decoration: BoxDecoration(
            borderRadius: BorderRadius.circular(20.w),
            border: Border.all(
              color: isSelected ? Colors.blue : Colors.white,
              width: isSelected ? 3 : 2,
            ),
            boxShadow: [
              BoxShadow(
                color:
                    isSelected
                        ? Colors.blue.withOpacity(0.4)
                        : Colors.black.withOpacity(0.2),
                blurRadius: isSelected ? 8 : 4,
                offset: Offset(0, isSelected ? 4 : 2),
              ),
            ],
          ),
          child: ClipRRect(
            borderRadius: BorderRadius.circular(17.w),
            child: Image.asset(
              location.locationImage,
              fit: BoxFit.cover,
              errorBuilder: (context, error, stackTrace) {
                return Container(
                  color: Colors.grey[300],
                  child: Icon(
                    Icons.person,
                    size: 20.sp,
                    color: Colors.grey[600],
                  ),
                );
              },
            ),
          ),
        ),

        SizedBox(height: 4.h),

        // 位置图标
        Image.asset(
          'assets/images/location.png',
          width: 16.w,
          height: 16.w,
          errorBuilder: (context, error, stackTrace) {
            return Icon(
              Icons.location_on,
              size: 16.sp,
              color: isSelected ? Colors.blue : Colors.red,
            );
          },
        ),
      ],
    ).inkWell(
      onTap: () {
        _onLocationTap(location);
      },
    );
  }

  // 处理位置点击
  void _onLocationTap(MapLocationEntity location) {
    setState(() {
      if (_selectedLocationId == location.locationId) {
        // 如果已选中，则取消选中
        _selectedLocationId = null;
        _animationController.reverse();
      } else {
        // 选中新的位置
        _selectedLocationId = location.locationId;
        _animationController.forward();
      }
    });

    // 显示用户详情弹窗
    _showUserProfileDialog(location);

    debugPrint(
      'Selected location: ${location.locationId}, User: ${location.userId}',
    );
  }

  // 显示用户详情弹窗
  void _showUserProfileDialog(MapLocationEntity location) {
    final user = userManager.getUserById(location.userId);
    if (user == null) return;

    showDialog(
      context: context,
      barrierDismissible: true,
      builder: (BuildContext context) {
        return Dialog(
          backgroundColor: Colors.transparent,
          insetPadding: EdgeInsets.symmetric(horizontal: 16.w),
          child: _buildUserProfileCard(user, location),
        );
      },
    );
  }

  // 构建用户资料卡片
  Widget _buildUserProfileCard(
    UserDataEntity user,
    MapLocationEntity location,
  ) {
    return Container(
      width: double.infinity,
      decoration: BoxDecoration(
        color: Colors.transparent, // 青绿色背景
        borderRadius: BorderRadius.circular(20.w),
      ),
      child: Stack(
        clipBehavior: Clip.none,
        children: [
          // 主要内容
          Container(
            decoration: BoxDecoration(
              color: const Color(0xFFCEF672),
              borderRadius: BorderRadius.circular(20.w),
            ),
            child: Column(
              mainAxisSize: MainAxisSize.min,
              children: [
                SizedBox(height: 50.h),

                // 用户名
                _buildUserName(user),

                SizedBox(height: 8.h),

                // 用户简介
                _buildUserBio(user),

                SizedBox(height: 20.h),

                // 统计数据
                _buildUserStats(user),

                SizedBox(height: 24.h),

                // 查看资料按钮
                _buildViewProfileButton(user),

                SizedBox(height: 16.h),

                // 位置图片
                _buildLocationImage(location),
              ],
            ),
          ),

          //用户头像
          Positioned(
            top: -40.w,
            left: 0,
            right: 0,
            child: Row(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [_buildUserAvatar(user)],
            ),
          ),

          // 关闭按钮
          Positioned(
            top: -40.w,
            right: 0.w,
            child: Container(
              width: 32.w,
              height: 32.w,
              decoration: BoxDecoration(
                color: Colors.white,
                shape: BoxShape.circle,
                boxShadow: [
                  BoxShadow(
                    color: Colors.black.withOpacity(0.1),
                    blurRadius: 4,
                    offset: Offset(0, 2),
                  ),
                ],
              ),
              child: Icon(
                Icons.close,
                size: 18.sp,
                color: Colors.black,
              ).center().inkWell(
                onTap: () {
                  Navigator.of(context).pop();
                },
              ),
            ),
          ),
        ],
      ),
    );
  }

  // 构建用户头像
  Widget _buildUserAvatar(UserDataEntity user) {
    return Container(
      width: 80.w,
      height: 80.w,
      decoration: BoxDecoration(
        shape: BoxShape.circle,
        border: Border.all(color: Colors.white, width: 1.w),
        image: DecorationImage(
          image: AssetImage(user.profileImage),
          fit: BoxFit.cover,
        ),
      ),
    );
  }

  // 构建用户名
  Widget _buildUserName(UserDataEntity user) {
    return Text(user.displayName.toUpperCase())
        .fontSize(20.sp)
        .fontFamily(GoogleFonts.poppins(fontWeight: FontWeight.w500).fontFamily)
        .textColor(Colors.black)
        .textAlignment(TextAlign.center);
  }

  // 构建用户简介
  Widget _buildUserBio(UserDataEntity user) {
    return Text(
      user.personalBio,
    ).fontSize(14.sp).textColor(Colors.black87).textAlignment(TextAlign.center);
  }

  // 构建用户统计数据
  Widget _buildUserStats(UserDataEntity user) {
    // 获取关注数据
    final followerCount = followManager.getFollowerCount(user.uniqueId);
    final followingCount = followManager.getFollowingCount(user.uniqueId);

    // 获取用户所有动态的点赞数总和
    final likeCount = socialManager.getUserTotalLikes(user.uniqueId);

    return Row(
      mainAxisAlignment: MainAxisAlignment.spaceEvenly,
      children: [
        _buildStatItem(followerCount.toString(), 'Follow'),
        _buildStatItem(followingCount.toString(), 'Following'),
        _buildStatItem(likeCount.toString(), 'Like'),
      ],
    );
  }

  // 构建单个统计项
  Widget _buildStatItem(String number, String label) {
    return Column(
      children: [
        Text(number).fontSize(16.sp).bold().textColor(Colors.black),
        SizedBox(height: 4.h),
        Text(label).fontSize(12.sp).textColor(const Color(0xFF666666)),
      ],
    );
  }

  // 构建查看资料按钮
  Widget _buildViewProfileButton(UserDataEntity user) {
    return Container(
      width: double.infinity,
      height: 48.h,
      margin: EdgeInsets.only(left: 16.w, right: 16.w),
      decoration: BoxDecoration(
        color: Color(0xFFF7CEBA),
        borderRadius: BorderRadius.circular(41.w),
        border: Border.all(color: Colors.black, width: 2),
        boxShadow: [
          BoxShadow(
            color: Color(0xFF000000),
            blurRadius: 0,
            offset: Offset(4, 4),
            spreadRadius: 0,
          ),
        ],
      ),
      child: Text('VIEW PROFILE')
          .fontSize(20.sp)
          .fontFamily(
            GoogleFonts.protestStrike(fontWeight: FontWeight.w400).fontFamily,
          )
          .textColor(Colors.black)
          .center()
          .inkWell(
            onTap: () {
              Navigator.of(context).pop();
              debugPrint('Navigate to user profile: ${user.uniqueId}');
            },
          ),
    );
  }

  // 构建位置图片
  Widget _buildLocationImage(MapLocationEntity location) {
    return Container(
      width: double.infinity,
      margin: EdgeInsets.only(top: 16.w, left: 16.w, right: 16.w, bottom: 16.w),
      height: 240.h,
      decoration: BoxDecoration(
        borderRadius: BorderRadius.circular(12.w),
        boxShadow: [
          BoxShadow(
            color: Colors.black.withOpacity(0.1),
            blurRadius: 8,
            offset: Offset(0, 4),
          ),
        ],
      ),
      child: ClipRRect(
        borderRadius: BorderRadius.circular(12.w),
        child: Image.asset(
          location.locationImage,
          fit: BoxFit.cover,
          errorBuilder: (context, error, stackTrace) {
            return Container(
              color: Colors.grey[300],
              child:
                  Icon(
                    Icons.image_not_supported,
                    size: 40.sp,
                    color: Colors.grey[600],
                  ).center(),
            );
          },
        ),
      ),
    );
  }
}
